package com.housekeeping.housekeeping.serviceItem.controller;

import com.housekeeping.housekeeping.serviceItem.utils.RequestUtils;
import com.housekeeping.housekeeping.serviceItem.utils.ResponseUtils;
import com.housekeeping.housekeeping.serviceItem.utils.StatUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * 根据图片名，图片归属删除图片
 * @reqParam img 图片名
 * @author tomyeung-李尐达
 */
@WebServlet("/Img/delete")
public class ImgDeleteController extends HttpServlet {
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String imgName = req.getParameter("img");
        //非空校验,非法名称校验
        if (imgName==null||imgName.indexOf("[")>=0||imgName.indexOf("]")>=0)
        {
            ResponseUtils.fail(resp, StatUtil.PARAMS_VALID);
            return;
        }
        String path = req.getServletContext().getRealPath("/img");
        File file = new File(path,imgName);
        //图片存在
        if (file.exists())
        {   //判断图片归属
            String aid = RequestUtils.verify(req);
            //根据最后一个'|'后面'.'前面的aid判断是否属于该用户
            int i=imgName.lastIndexOf("[");
            int j=imgName.lastIndexOf("]");
            if (i>=0&&j>0&&imgName.substring(i,j).equals(aid)){
                //属于该用户的图片，允许删除
                file.delete();
                ResponseUtils.success(resp,StatUtil.SUCCESS);
            }
            else {
                //非法操作，拒绝
                ResponseUtils.fail(resp,StatUtil.INTERNET_ERR);
            }
        }
        //图片不存在，返回错误信息
        else {ResponseUtils.fail(resp,StatUtil.IMAGE_NOT_FOUND);}
    }
}
